package com.szy.bigevent.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.szy.bigevent.config.AliOssConfig;
import com.szy.bigevent.service.AliOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.concurrent.CompletableFuture;

@Service
public class AliOssServiceImpl implements AliOssService {

    @Autowired
    private OSS ossClient;

    @Autowired
    private AliOssConfig aliOssConfig;

    @Override
    public String upload(String fileName, InputStream inputStream) {
        try {
            ossClient.putObject(aliOssConfig.getBucketName(), fileName, inputStream);
        }catch (OSSException oe){
            System.out.println("AliOss upload OSSException ErrorMessage:"+oe.getErrorMessage());
            System.out.println("AliOss upload OSSException Message:"+oe.getMessage());

        }catch (ClientException ce){
            System.out.println("AliOss upload ClientException ErrorMessage:"+ce.getErrorMessage());
            System.out.println("AliOss upload ClientException Message:"+ce.getMessage());
        }
        /**
         * 构造文件上传后的访问路径
         *  eg:   https://cyx-big-event.oss-cn-hangzhou.aliyuncs.com
         *          /254de4e2-0555-409a-ba00-634515cd8909.jpg
         */
        StringBuffer url = new StringBuffer();
        url.append("https://");
        url.append(aliOssConfig.getBucketName());
        url.append(".");
        url.append(aliOssConfig.getEndPoint());
        url.append("/");
        url.append(fileName);
        return url.toString();
    }

    @Async
    @Override
    public CompletableFuture<Boolean> delete(String url) {
        //更具路径获取文件名称
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        try {
            System.out.println("开始删除文件"+fileName+"....");
            ossClient.deleteObject(aliOssConfig.getBucketName(), fileName);
            System.out.println("AliOss delete success:"+fileName);
            return CompletableFuture.completedFuture(true);
        }catch (OSSException oe){
            System.out.println("AliOss delete OSSException ErrorMessage:"+oe.getErrorMessage());
            System.out.println("AliOss delete OSSException Message:"+oe.getMessage());
            return  CompletableFuture.completedFuture(false);
        }catch (ClientException ce){
            System.out.println("AliOss delete ClientException ErrorMessage:"+ce.getErrorMessage());
            System.out.println("AliOss delete ClientException Message:"+ce.getMessage());
            return  CompletableFuture.completedFuture(false);
        }
    }
}

